package com.qbw.app.module.home.holder;

import android.content.Context;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.databinding.ViewDataBinding;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.lib.util.DateTimeUtil;
import com.lib.util.ScreenUtil;
import com.lib.util.StringUtil;
import com.qbw.app.R;
import com.qbw.app.databinding.HomeHolderTravelBinding;
import com.qbw.app.model.Travel;
import com.qbw.app.module.common.holder.CommonHolder;
import com.qbw.app.module.vehicle.VehicleDataBindingAdapter;
import com.qbw.app.module.vehicle.activity.VehicleTravelDetailActivity;
import com.qbw.core.observable.ObservableBoolean;

import java.util.List;
import java.util.Locale;

/**
 * 首页行程
 * @author xiansx
 * @date 2020/10/12
 */
public class HomeTravelHolder extends CommonHolder<Travel, HomeHolderTravelBinding> {

    public static final int IN_HOME = 1;
    public static final int IN_TRAVEL_LIST = 2;
    public static final int IN_TRAVEL_DETAIL = 3;

    private ObservableBoolean mShowTimeViews = new ObservableBoolean();

    public HomeTravelHolder(Context context, ViewGroup viewParent, Object listener) {
        super(context, R.layout.home_holder_travel, viewParent, listener);
        init();
    }

    public HomeTravelHolder(Context context, ViewDataBinding binding, Object listener) {
        super(context, binding);
        mListener = listener;
        init();
    }

    private void init() {
        if (mListener instanceof Listener) {
            int in = ((Listener) mListener).onGetWhereHomeTravelHolderIn();
            mBinding.tvLastStroke.setText(in == IN_HOME ? R.string.travel_latest : R.string.travel_time);
            mBinding.tvTravelAll.setVisibility(in == IN_HOME ? View.VISIBLE : View.GONE);
            mShowTimeViews.setValue(in == IN_TRAVEL_DETAIL);
            if (in == IN_TRAVEL_LIST) {
                ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) mBinding.vLineUnderShichang
                        .getLayoutParams();
                params.bottomMargin = ScreenUtil.dp2px(mContext, 15);
            }
        }
    }

    @Override
    public void bindData(int position, Travel data) {
        super.bindData(position, data);
        mBinding.setTravel(data);
        mBinding.setShowTimeViews(mShowTimeViews);
        mBinding.executePendingBindings();
        Travel.Point point = data.getStartPoint();
        if (point != null) {
            VehicleDataBindingAdapter.setDateYearMonthDay(mBinding.tvLastStrokeValue,
                                                          data.getStartPoint().getTime());
            //VehicleDataBindingAdapter.setVehicleLocatinTime(mBinding.tvStartTime, point.getTime());
            mBinding.tvStartTime.setText(DateTimeUtil.formatHHMM(point.getTime()));
            mBinding.tvStartAddress.setText(point.getAddress());
        }
        point = data.getEndPoint();
        if (point != null) {
            //VehicleDataBindingAdapter.setVehicleLocatinTime(mBinding.tvParkTime, point.getTime());
            mBinding.tvParkTime.setText(DateTimeUtil.formatHHMM(point.getTime()));
            mBinding.tvParkAddress.setText(point.getAddress());
        }
        mBinding.tvDrivingScoreValue.setText(String.valueOf((int) data.getScore()));
        //mBinding.tvDistanceValue.setText(formatValue(data.getMile()) + "KM");
        VehicleDataBindingAdapter.setDistance(mBinding.tvDistanceValue, data.getMile());
        //mBinding.tvOilEconomyValue.setText(formatValue(data.getAvgFuel()) + "L/100KM");
        VehicleDataBindingAdapter.setOilUseOfHundredKm(mBinding.tvOilEconomyValue,
                                                       data.getAvgFuel());
        //mBinding.tvMaxSpeedValue.setText(formatValue(data.getMaxSpeed()) + "KM/H");
        if (data.getMaxSpeed() >= data.getAvgSpeed()) {
            VehicleDataBindingAdapter.setSpeedHour(mBinding.tvMaxSpeedValue, data.getMaxSpeed());
        } else {
            VehicleDataBindingAdapter.setSpeedHour(mBinding.tvMaxSpeedValue, -1d);
        }
        formatTimeDuration(mBinding.tvTimeDurationValue, data.getDriverTime());
        //mBinding.tvOilUsedValue.setText(formatValue(data.getFuel()) + "L");
        VehicleDataBindingAdapter.setOilUse(mBinding.tvOilUsedValue, data.getFuel());
        //mBinding.tvAverageSpeedValue.setText(formatValue(data.getAvgSpeed()) + "KM/H");
        VehicleDataBindingAdapter.setSpeedHour(mBinding.tvAverageSpeedValue, data.getAvgSpeed());
        mBinding.tvTravelAll.setOnClickListener(mClickListenerAll);
        itemView.setOnClickListener(mClickListenerItem);
    }

    @Override
    protected void onClickItem() {
        if (mListener instanceof Listener) {
            int in = ((Listener) mListener).onGetWhereHomeTravelHolderIn();
            if (in == IN_TRAVEL_DETAIL) {
                return;
            } else {
                VehicleTravelDetailActivity.startActivity(mContext, mData);
            }
        } else {
            VehicleTravelDetailActivity.startActivity(mContext, mData);
        }
    }

    private String formatValue(double v) {
        return String.format("%.2f", v);
    }

    private void formatTimeDuration(TextView textView, double duration) {
        String sd = String.format(Locale.getDefault(), "%f", duration);
        StringBuilder sbDuration = new StringBuilder();
        if (sd.contains(".")) {
            List<String> sdParts = StringUtil.strings(sd, "\\.", true);
            if (sdParts.size() >= 2) {
                int hour = Integer.parseInt(sdParts.get(0));
                int minute = (int) (Double.parseDouble("0." + sdParts.get(1)) * 60);
                if (hour > 0) {
                    sbDuration.append(hour).append("h");
                }
                sbDuration.append(minute).append(hour > 0 ? "m" : "min");
            }
        } else {
            sbDuration.append(sd).append("h");
        }
        SpannableString ss = new SpannableString(sbDuration);
        int i = sbDuration.indexOf("h");
        if (i >= 0) {
            AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan((int) (textView.getTextSize() / 2));
            ss.setSpan(sizeSpan, i, i + 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        }
        i = sbDuration.indexOf("min");
        if (i >= 0) {
            AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan((int) (textView.getTextSize() / 2));
            ss.setSpan(sizeSpan, i, i + 3, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        } else {
            i = sbDuration.indexOf("m");
            if (i > 0) {
                AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan((int) (textView.getTextSize() / 2));
                ss.setSpan(sizeSpan, i, i + 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            }
        }
        textView.setText(ss);
    }

    private View.OnClickListener mClickListenerAll = v -> {
//        VehicleTravelListActivity.start(mContext, mData.getVehicle());
    };

    public interface Listener {
        int onGetWhereHomeTravelHolderIn();
    }
}
